package com.chwn.curiousdiary.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.NotificationTarget;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.bean.StoryBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.receiver.StatusBarReceiver;
import com.chwn.curiousdiary.ui.play.activity.StoryPlayActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Myshikin on 2017/7/25.
 */

public class Notifier {

    private static final int NOTIFICATION_ID = 0x111;
    private static AudioService        playService;
    private static NotificationManager notificationManager;
    private static NotificationTarget  notificationTarget;

    public static void init(AudioService playService) {
        Notifier.playService = playService;
        notificationManager = (NotificationManager) playService.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public static void showPlay(StoryBean bean) {
        playService.startForeground(NOTIFICATION_ID, buildNotification(playService, bean, true));
    }

    public static void showPause(StoryBean bean) {
        playService.stopForeground(false);
        notificationManager.notify(NOTIFICATION_ID, buildNotification(playService, bean, false));
    }

    public static void showPause(StoryBean bean , boolean isCancel) {
        playService.stopForeground(false);
        notificationManager.notify(NOTIFICATION_ID, buildNotification(playService, bean, false , isCancel));
    }

    public static void cancelAll() {
//                notificationManager.cancelAll();
        notificationManager.cancel(NOTIFICATION_ID);

    }


    private static Notification buildNotification(Context context, StoryBean bean, boolean isPlaying) {
        Intent intent = new Intent(context, StoryPlayActivity.class);
        intent.putExtra(Constant.STORY_SERVICE_TYPE, AudioService.FROM_MAIN);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        RemoteViews remoteViews = getRemoteViews(context, bean, isPlaying);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.icon_small_luncher)
                .setCustomContentView(remoteViews);

        Notification notification = builder.build();

        notificationTarget = new NotificationTarget(
                context,
                remoteViews,
                R.id.iv_notify_img,
                notification,
                NOTIFICATION_ID);

        Glide.with(context.getApplicationContext()) // safer!
                .load(bean.getStoryImage())
                .asBitmap()
                .placeholder(R.drawable.icon_one_to_one)
                .into(notificationTarget);

        return notification;
    }

    private static Notification buildNotification(Context context, StoryBean bean, boolean isPlaying , boolean cancel) {
        Intent intent = new Intent(context, StoryPlayActivity.class);
        intent.putExtra(Constant.STORY_SERVICE_TYPE, AudioService.FROM_MAIN);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        RemoteViews remoteViews = getRemoteViews(context, bean, isPlaying);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.icon_small_luncher)
                .setCustomContentView(remoteViews);

        Notification notification = builder.build();

        notificationTarget = new NotificationTarget(
                context,
                remoteViews,
                R.id.iv_notify_img,
                notification,
                NOTIFICATION_ID);

        Glide.with(context.getApplicationContext()) // safer!
                .load(bean.getStoryImage())
                .asBitmap()
                .placeholder(R.drawable.icon_one_to_one)
                .into(notificationTarget);

        return notification;
    }

    private static RemoteViews getRemoteViews(Context context, StoryBean bean, boolean isPlaying) {
        String title = bean.getTitle();

        Bitmap cover = null;

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notify_audio);

        /*if (cover != null) {
            remoteViews.setImageViewBitmap(R.id.iv_notify_img, cover);
        } else {
            remoteViews.setImageViewResource(R.id.iv_notify_img, R.drawable.icon_story_placeholder);
        }*/

        remoteViews.setTextViewText(R.id.tv_notify_title, title);

        Intent playIntent = new Intent(StatusBarReceiver.ACTION_STATUS_BAR);
        playIntent.putExtra(StatusBarReceiver.EXTRA, StatusBarReceiver.EXTRA_PLAY_PAUSE);
        PendingIntent playPendingIntent = PendingIntent.getBroadcast(context, 0, playIntent, 0);
        remoteViews.setImageViewResource(R.id.iv_notify_play, getPlayIconRes(isPlaying));
        remoteViews.setOnClickPendingIntent(R.id.iv_notify_play, playPendingIntent);

        Intent nextIntent = new Intent(StatusBarReceiver.ACTION_STATUS_NEXT);
        nextIntent.putExtra(StatusBarReceiver.EXTRA, StatusBarReceiver.EXTRA_NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0, nextIntent, 0);
        remoteViews.setImageViewResource(R.id.iv_notify_next, R.drawable.icon_nm_next);
        remoteViews.setOnClickPendingIntent(R.id.iv_notify_next, nextPendingIntent);

        Intent proIntent = new Intent(StatusBarReceiver.ACTION_STATUS_PRO);
        proIntent.putExtra(StatusBarReceiver.EXTRA, StatusBarReceiver.EXTRA_PRO);
        PendingIntent proPendingIntent = PendingIntent.getBroadcast(context, 0, proIntent, 0);
        remoteViews.setImageViewResource(R.id.iv_notify_pre, R.drawable.icon_nm_pro);
        remoteViews.setOnClickPendingIntent(R.id.iv_notify_pre, proPendingIntent);

        Intent closeSelfIntent = new Intent(StatusBarReceiver.ACTION_STATUS_CLOSE);
        closeSelfIntent.putExtra(StatusBarReceiver.EXTRA, StatusBarReceiver.EXTRA_CLOSE_SELF);
        PendingIntent closeSelfPendingIntent = PendingIntent.getBroadcast(context, 0, closeSelfIntent, 0);
        remoteViews.setImageViewResource(R.id.iv_notify_close, R.drawable.icon_nm_close);
        remoteViews.setOnClickPendingIntent(R.id.iv_notify_close, closeSelfPendingIntent);

        return remoteViews;
    }

    private static int getPlayIconRes(boolean isPlaying) {
        if (isPlaying) {
            return R.drawable.icon_nm_stop;
        } else {
            return R.drawable.icon_nm_play;
        }
    }

    private static int getNotificationTextColor(Context context) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        Notification notification = builder.build();
        RemoteViews remoteViews = notification.contentView;
        if (remoteViews == null) {
            return Color.BLACK;
        }
        int layoutId = remoteViews.getLayoutId();
        ViewGroup notificationLayout = (ViewGroup) LayoutInflater.from(context).inflate(layoutId, null);
        TextView title = (TextView) notificationLayout.findViewById(android.R.id.title);
        if (title != null) {
            return title.getCurrentTextColor();
        } else {
            return findTextColor(notificationLayout);
        }
    }

    /**
     * 如果通过 android.R.id.title 无法获得 title ，
     * 则通过遍历 notification 布局找到 textSize 最大的 TextView ，应该就是 title 了。
     */
    private static int findTextColor(ViewGroup notificationLayout) {
        List<TextView> textViewList = new ArrayList<>();
        findTextView(notificationLayout, textViewList);

        float maxTextSize = -1;
        TextView maxTextView = null;
        for (TextView textView : textViewList) {
            if (textView.getTextSize() > maxTextSize) {
                maxTextView = textView;
            }
        }

        if (maxTextView != null) {
            return maxTextView.getCurrentTextColor();
        }

        return Color.BLACK;
    }

    private static void findTextView(View view, List<TextView> textViewList) {
        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                findTextView(viewGroup.getChildAt(i), textViewList);
            }
        } else if (view instanceof TextView) {
            textViewList.add((TextView) view);
        }
    }

    private static boolean isSimilarColor(int baseColor, int color) {
        int simpleBaseColor = baseColor | 0xff000000;
        int simpleColor = color | 0xff000000;
        int baseRed = Color.red(simpleBaseColor) - Color.red(simpleColor);
        int baseGreen = Color.green(simpleBaseColor) - Color.green(simpleColor);
        int baseBlue = Color.blue(simpleBaseColor) - Color.blue(simpleColor);
        double value = Math.sqrt(baseRed * baseRed + baseGreen * baseGreen + baseBlue * baseBlue);
        return value < 180.0;
    }

    public static void onDestory() {
        playService = null;
        notificationManager = null;

    }
}
